import {
  baseUrl
} from '../../../config/api';
import Message from 'tdesign-miniprogram/message/index';

Page({
  data: {
    password:'',
    newPassword:'',
    newPasswordRe:'',
    userId: -1,
    type: -1,
    isBtnDisabled: true,
    mobile: '',
    personInfo: {
      avatarUrl: '',
      nickName: '',
      gender: 0,
      phoneNumber: '',
      class: '',
      sNumber: '',
    },
  },
  onLoad(options) {
    console.log(options)
    this.setData({
      userId: options.id,
      mobile: options.mobile,
      type: options.type
    });
    wx.setNavigationBarTitle({
      title: '修改密码'
    })
  },

  validateForm(){
    if (this.data.newPassword !== this.data.newPasswordRe) {
      Message.error({
        offset: [10, 12],
        duration: 1500,
        content: '两次输入的密码不同，请重新输入',
        closeBtn: true,
      });
      return false;
    } else if (!this.checkPasswordComplexity(this.data.newPassword)) {
      // 密码复杂度校验失败，checkPasswordComplexity 函数内部已经显示了错误信息
      return false;
    } else {
      return true;
    }
  },

  onSubmit() {
    console.log(this.data)
    if (this.data.userId === -1) {
      return
    }

    if (!this.validateForm()){
      return;
    }

    wx.showLoading({
      title: '修改中...',
    })
    wx.request({
      url: baseUrl + 'sys/user/wxChangePassword',
      method: 'post',
      data: {
        userId: this.data.userId,
        password: this.data.password,
        newPassword: this.data.newPassword,
        mobile: this.data.mobile,
      },
      success: (res) => {
        wx.hideLoading()
        if (res.data.code === 0) {
          Message.success({
            context: this,
            offset: [10, 12],
            duration: 1500,
            content: '修改密码成功，下次登录时生效',
            closeBtn: true,
          });
          setTimeout( () => {
            wx.navigateBack()
          },1500)
        } else {
          Message.error({
            context: this,
            offset: [10, 12],
            duration: 2000,
            content: res.data.msg,
            closeBtn: true,
          });
        }
      }
    })
  },

  checkPasswordComplexity(password) {
    if (!password || password.length < 8) {
      Message.error({
        offset: [10, 12],
        duration: 1500,
        content: '密码至少需要8位',
        closeBtn: true,
      });
      return false;
    }
  
    const hasLetter = /[a-zA-Z]/.test(password);
    const hasNumber = /\d/.test(password);
  
    if (!(hasLetter && hasNumber)) {
      Message.error({
        offset: [10, 12],
        duration: 1500,
        content: '密码必须包含字母和数字',
        closeBtn: true,
      });
      return false;
    }
  
    return true;
  },

  init() {

  },
});